<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\Assets;
use app\common\model\Bank;
use app\common\model\Relation;
use app\common\model\UserNumber;
use app\common\model\UserRelease;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\View;
use app\common\model\User as UserModel;

class User extends Base
{

    public function index()
    {
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    public function info()
    {
        return View::fetch();
    }

    public function agent()
    {
        $users = \app\common\model\Address::where(['city'=>$this->user->is_agent,'is_del'=>0,'default'=>1])->Distinct(true)->field('uid')->column('uid');
        $user_num = count($users);
        $agency_income = $this->user->agency_income;
        $order_ids = \addons\V2\admin\model\Order::where(['city'=>$this->user->is_agent])->column('id');
        $order_sum = count($order_ids);
        $real_amount = \addons\V2\admin\model\Order::whereIn('id',$order_ids)->sum('real_amount');
        View::assign(['agency_income'=>$agency_income,'user_num'=>$user_num,'order_sum'=>$order_sum,'real_amount'=>$real_amount]);
        return View::fetch();
    }

    public function setting()
    {
        return View::fetch();
    }

    public function contact()
    {
        return View::fetch();
    }

    public function my_team()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1);
            $map = ['uid' => $this->user->id, 'algebra' => 1];
            return json(Relation::getPageList($map, '*', $page, 20, false, ['fresh']));
        }
        $dpn = Relation::where(['uid' => $this->user->id, 'algebra' => 1])->column('new_uid');
        $team = Relation::where('uid', $this->user->id)->column('new_uid');
//        $team[] = $this->user->id;
        View::assign([
            'dpn'        => count($dpn),
            'dpn_total'  => UserModel::whereIn('id', $dpn)->sum('my_total'),
            'team'       => count($team),
            'team_total' => $this->user->team_total,
        ]);
        return View::fetch();
    }

    public function methodList()
    {
        return View::fetch();
    }

    public function method($type)
    {
        $mode = ['alipay' => '支付宝', 'wechat' => '微信', 'bank' => '银行卡', 'usdt' => 'USDT', 'lsc' => 'LSC'];
        View::assign([
            'type'      => $type,
            'title'     => $mode[$type],
            'bank_list' => Bank::where(['status' => 1, 'is_del' => 0])->column('title', 'id')
        ]);
        return View::fetch();
    }

    public function exchange()
    {
        View::assign(['user'=>$this->user]);
        return View::fetch();
    }

    public function exchange_save()
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            UserModel::update($param, ['id' => $this->user->id]);

            return json(['code' => 1, 'msg' => '已保存']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }



    public function method_save($type)
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            if ($type == 'usdt') {
                if (!$param['usdt_address']) {
                    return json(['code' => -1, 'msg' => '请填写usdt账号']);
                }
            }elseif($type == 'lsc') {
                if (!$param['lsc_address']) {
                    return json(['code' => -1, 'msg' => '请填写lsc账号']);
                }
            }else {
                $v = $type == 'bank' ? 'MethodBank' : 'MethodImg';
                try {
                    $this->validate($param, $v);
                } catch (ValidateException $e) {
                    return json(['code' => -1, 'msg' => $e->getError()]);
                }
            }
            switch ($type) {
                case "bank":
                case "usdt":
                case "lsc":
                    break;
                default:
                    $param[$type . '_name'] = $param['name'];
                    $param[$type . '_image'] = $param['image'];
                    unset($param['name']);
                    unset($param['image']);
            }

            UserModel::update($param, ['id' => $this->user->id]);

            return json(['code' => 1, 'msg' => '已保存']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function edit()
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            UserModel::update($param, ['id' => $this->user->id]);
            return Result::success('已修改');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }

    public function logout()
    {
        $token = md5(time() . $this->user['id'] . $this->request->ip());

        UserModel::update([
            'token' => $token
        ], ['id' => $this->user['id']]);
        cookie('token', null);

        return Result::fastReturn(['code' => 1, 'msg' => '已退出登录', 'url' => url('login/index')->build()]);
    }

    public function share()
    {
        $url = "http://" . $_SERVER['SERVER_NAME'] . "/index/register/index.html?code=" . $this->user->code;
        View::assign('url', $url);
        return View::fetch();
    }

    public function release()
    {
        if ($this->request->isAjax()) {
            return Result::fastReturn(UserRelease::getPageList(['uid' => $this->user->id], '*', $this->getPage(), 20, false));
        }
        return View::fetch();
    }

    public function switchAccount()
    {
        $list = UserNumber::where('uid', $this->user->id)->with('take')->select();
        View::assign('list', $list);
        return View::fetch();
    }

    public function addAccount()
    {
        $param = $this->request->post();
        $user = \app\common\model\User::where('code', $param['code'])->where('delete_time', 0)->find();
        if (empty($user)) return Result::fail('账号不存在');

        if ($user['password'] != md5($param['password'])) {
            return Result::fail('密码错误');
        }
        if ($user['is_lock'] == 1) {
            return Result::fail('账号不存在');
        }

        $info = UserNumber::where(['account_uid' => $user->id, 'uid' => $this->user->id])->find();
        if ($info) {
            return Result::fail('您已经添加过此账号了，请勿重复添加');
        }

        UserNumber::create(['uid' => $this->user->id, 'account_uid' => $user->id]);
        return Result::success('添加成功');
    }

    public function editAccount()
    {
        $param = $this->request->post();
        if ($param['type'] == 1) {
            UserNumber::where('id', $param['id'])->delete();
            return Result::success('已删除');
        } else {
            $info = UserNumber::where('id', $param['id'])->find();
            if ($info->take->token) {
                cookie('token', $info->take->token);
            } else {
                $token = md5(time() . $this->request->ip() . $info->take->id);
                \app\common\model\User::update(['token' => $token, 'id' => $info->account_uid]);
                cookie('token', $token);
            }
        }
        return Result::success('切换成功');
    }

}

